package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.param.UserLoginParam;
import com.atguigu.gulimall.auth.param.UserRegistParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : mayp
 * @Date: 2020-11-03 21:06
 */
@Controller
public class LoginController {
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    //    重定向到错误页面，注册页面
    private final String REDIRECT_ERROR_PAGE = "redirect:http://auth.gulimall.com/reg.html";
    //    重定向正确页面。登录页面
    private final String LOGIN_PAGE = "redirect:http://auth.gulimall.com/login.html";
    //    登录页
    private final String LOGIN_USER = "redirect:http://gulimall.com";

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/smsService/sendsms/send/{phone}")
    public R phoneCode(@PathVariable("phone") String phone) {
        R r = thirdPartyFeignService.phoneCode(phone);
        if (r.getCode() != 0) {
            return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
        }
        return r.ok();
    }

    /**
     * Model model替换成RedirectAttributes 可以重定向携带数据
     * //            封装到Map集合中。key是Field,value是DefaultMessage
     * /*Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
     * return fieldError.getField();
     * }, fieldError -> {
     * return fieldError.getDefaultMessage();
     * }));
     *
     * @param param
     * @param result
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistParam param, BindingResult result, RedirectAttributes redirectAttributes) {
//        如果出现错误信息
        if (result.hasErrors()) {
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            封装到mvc的视图中
//            model.addAttribute("errors",collect);
            redirectAttributes.addFlashAttribute("errors", collect);
//            如果出现错误，还是在注册页面
            return REDIRECT_ERROR_PAGE;
        }
//        1、校验验证码（调用远程短信服务）
        String code = param.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + param.getPhone());
//        如果验证码不为空
        if (!StringUtils.isEmpty(s)) {
//            如果验证码与redis中的一样
            if (code.equals(s)) {
//                /删除验证码，令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + param.getPhone());
//                验证通过，真正注册，调用远程服务注册
                R regist = memberFeignService.regist(param);
                if (regist.getCode() == 0) {
//                    注册成功
                    return LOGIN_PAGE;
                } else {
//                    错误
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", regist.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return REDIRECT_ERROR_PAGE;
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return REDIRECT_ERROR_PAGE;
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return REDIRECT_ERROR_PAGE;
        }
    }

    /**
     * 社交登录
     */
    @PostMapping("/login")
    public String login(UserLoginParam param, RedirectAttributes redirectAttributes,
                        HttpSession session) {
//        远程登录
        R login = memberFeignService.login(param);
        if (login.getCode() == 0) {
            //        登录成功跳转首页
            MemberResVo data = login.getData("data", new TypeReference<MemberResVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_SESSION_LOGIN_USER, data); // 把用户信息存储到redis的session
            return LOGIN_USER;
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", login.getData("msg", new TypeReference<String>() {
        }));
        redirectAttributes.addFlashAttribute("errors", errors);
        return LOGIN_PAGE;
    }

    /**
     * 如果已经登录过，就不能跳转到登录页
     */
    @GetMapping("login.html")
    public String login(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_SESSION_LOGIN_USER);
        if (null == attribute) {
            return "login";
        }
//        跳转登录页
        return LOGIN_USER;
    }
}
